package com.example.designpattern.lazyloading;

import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;

/**
 * 这个懒加载模式是线程安全的，而且比HolderThreadSafe效率更高
 * 使用了jdk8的新特性Supplier作为一个Heavy工厂
 */
@Slf4j
public class Java8Holder {

  private Supplier<Gift> heavy = this::createAndCacheHeavy;

  public Java8Holder() {
  }

  public Gift getHeavy() {
    return heavy.get();
  }

  private synchronized Gift createAndCacheHeavy() {
    // 局部内部类
    class HeavyFactory implements Supplier<Gift> {
      private final Gift heavyInstance = new Gift();

      @Override
      public Gift get() {
        return heavyInstance;
      }

    }

    if (!(heavy instanceof HeavyFactory)) {
      heavy = new HeavyFactory();
    }

    return heavy.get();

  }

}
